package com.zzl.alligator.management.system.controller;

import cn.hutool.core.map.MapUtil;
import com.zzl.alligator.common.constant.ProjectProperties;
import com.zzl.alligator.common.enums.BusinessTypeEnum;
import com.zzl.alligator.common.util.SecurityUtils;
import com.zzl.alligator.common.util.ServletUtils;
import com.zzl.alligator.common.util.file.FileUploadUtils;
import com.zzl.alligator.framework.aspectj.annotation.Log;
import com.zzl.alligator.framework.security.LoginUser;
import com.zzl.alligator.framework.security.service.TokenService;
import com.zzl.alligator.framework.support.web.vo.JsonResult;
import com.zzl.alligator.management.system.domain.SysUser;
import com.zzl.alligator.management.system.service.impl.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * 个人信息
 *
 * @author zhouziliang
 * @since 2020/7/3
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysPersonalInfoController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserService userService;

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping
    public JsonResult info() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return JsonResult.error("获取用户信息失败");
        }
        SysUser user = loginUser.getUser();
        String roles = userService.findUserRoleGroupByUserName(user.getUserName());
        String posts = userService.findUserPostByUserId(user.getUserName());
        Map<Object, Object> map = MapUtil.builder()
                .put("user", user)
                .put("roleGroup", roles)
                .put("postGroup", posts)
                .build();
        return JsonResult.success(map);

    }

    /**
     * 更新用户
     *
     * @param user 用户
     * @return 更新结果
     */
    @PutMapping
    @Log(title = "修改个人信息", businessType = BusinessTypeEnum.UPDATE)
    public JsonResult updateUser(@RequestBody SysUser user) {
        int res = userService.updateUserProfile(user);
        if (res > 0) {
            //更新成功
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setNickName(user.getNickName());
            loginUser.getUser().setPhonenumber(user.getPhonenumber());
            loginUser.getUser().setEmail(user.getEmail());
            loginUser.getUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return JsonResult.success();
        }
        return JsonResult.error("更新用户信息失败");
    }

    /**
     * 修改密码
     *
     * @param oldPassword 老密码
     * @param newPassword 新密码
     * @return 修改结果
     */
    @PutMapping("/password")
    @Log(title = "修改密码", businessType = BusinessTypeEnum.UPDATE)
    public JsonResult updatePassword(String oldPassword, String newPassword) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return JsonResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return JsonResult.error("新密码不能与旧密码相同");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(loginUser.getUser().getUserId());
        sysUser.setUserName(userName);
        sysUser.setPassword(SecurityUtils.encryptPassword(newPassword));
        if (userService.resetUserPwd(sysUser) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return JsonResult.success();
        }
        return JsonResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public JsonResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            String avatar = FileUploadUtils.upload(ProjectProperties.getInstance().getAvatarPath(), file);
            if (userService.updateUserAvatar(
                    new SysUser() {{
                        setUserName(loginUser.getUsername());
                        setAvatar(avatar);
                    }}) > 0
            ) {
                JsonResult ajax = JsonResult.success(avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return JsonResult.error("上传图片异常，请联系管理员");
    }
}
